/**
 * Created by wangxin on 2017-9-26 10:02:01.
 */

'use strict';
const page = {
    url: {
        // loadSignUI: Dolphin.path.mengkePath + '/api/bonus/config?token='+contextData.data.gId,
        // loadRecord: Dolphin.path.mengkePath + '/api/bonus/record?token='+contextData.data.gId,
        // sign: Dolphin.path.mengkePath + '/api/bonus/sign?token='+contextData.data.gId,
        sign: Dolphin.path.contextPath + '/work/sign/'+contextData.data.gId,
        loadSignUI: Dolphin.path.contextPath + '/work/bonus/config/'+contextData.data.gId,
        loadRecord: Dolphin.path.contextPath + '/work/bonus/record/'+contextData.data.gId,
    },
    container: $('#container'),
    calendarDate: $('#calendarDate'),
    recordPanel: $('#recordPanel'),
    pageFooterLogo: $('.pageFooter img'),

    UIConfig : null,
    recordData: null,
    totalData: null,
};

page.init = function () {
    page.initElement();
    page.initEvent();
};

page.initElement = function () {
    let thisPage = this;
    this.renderCalendar();
    Dolphin.ajax({
        url: thisPage.url.loadSignUI,
        type: "get",
        forceUrl: 'true',
        onSuccess: function (data) {
            thisPage.UIConfig = data.data;
            thisPage.renderData();
        },
        onError: function (e) {
            alert('网络出错啦，请您重新加载');
        }
    });
    this.getData();
};

page.initEvent = function () {

    let thisPage = this;
    let userInfo = {
        openId: contextData.userData.openid,
        unionId: contextData.userData.unionid,
        name: contextData.userData.vipName,
        cardCode: contextData.userData.cardCode,
        mobile: contextData.userData.mobile,
        nickName: contextData.userData.nickname,
    };
    $('#todayFlag').click(function(){
        Dolphin.ajax({
            url: thisPage.url.sign,
            type: "post",
            forceUrl: true,
            async: false,
            data: JSON.stringify(userInfo),
            onSuccess: function (data) {
                // let message = data.message;
                // if(data.data.point){
                //     message += '　积分+' + data.data.point
                // }
                // Dolphin.alert(message);
                thisPage.alert('签到成功', '恭喜您获得 ' + data.data.point + ' 积分');
                thisPage.getData();
            },
            onError: function (e) {
                // Dolphin.alert(e.message || '网络出错啦，请您重新加载');
                thisPage.alert('签到失败', e.message || '网络出错啦，请您重新加载');
            }
        });
    });
    $('.goBack').click(function(){
        history.back();
    })

    $('.signInfoModel, .signInfoButton button, .signInfoClose').click(function(){
        $('.signInfo').hide();
    })
};

page.getData = function(){
    let thisPage = this;
    Dolphin.ajax({
        url: thisPage.url.loadRecord,
        type: "get",
        forceUrl: 'true',
        data: {openId: contextData.userData.openid},
        onSuccess: function (data) {
            thisPage.recordData = data.record || [];
            thisPage.totalData = data.total || {};
            thisPage.renderData();
        },
        onError: function (e) {
            alert('网络出错啦，请您重新加载');
        }
    });
};
page.renderData = function(){
    if(this.UIConfig && this.recordData){
        this.renderRecordData();
        this.renderUIConfig();
        this.renderTotalData();
    }
};
page.renderRecordData = function(){
    let thisPage = this;
    let today = new Date().getDate();
    $('td[day] .signFlag').remove();
    thisPage.recordPanel.empty();

    this.recordData.forEach(function(record){
        let day = Number(record['day'] && record['day'].substr(-2, 2));
        $('td[day="'+day+'"]').append($('<i class="signFlag">'));

        let recordItem = $('<div class="recordItem">').appendTo(thisPage.recordPanel);
        recordItem.append(record.day);
        let result = $('<span>').appendTo(recordItem);
        if(record.point){
            result.addClass('point').html(record.point);
        }else if(record.couponCode){
            result.addClass('coupon').html('礼券');
        }

        if(today === day){
            $('#todayFlag').html('已签到')
        }
    });
};
page.renderUIConfig = function(){
    let mainColor = this.UIConfig['mainColor'] || 'rgb(227, 79, 116)';
    $('.calendarPanel, .calendarPanel .calendarPanelBody .totalPoint, .calendarPanel .calendarPanelBody .calendarBody td .signFlag, .signInfo .signInfoPanel .signInfoButton button').css('background', mainColor);
    $('.calendarPanel .calendarPanelBody .todayFlag').css('box-shadow', '0 0 10px ' + mainColor);
    $('.calendarPanel .calendarPanelBody .calendarBody td.today, .signInfo .signInfoPanel .signInfoTitle').css('color', mainColor);
    $('.pageFooter').css('background', this.UIConfig['footerBg'] || '#eee');
    if(this.UIConfig['footerLogo']){
        this.pageFooterLogo.attr('src',Dolphin.path.mengkeUploadPath + this.UIConfig['footerLogo']);
    }else{
        this.pageFooterLogo.attr('src',Dolphin.path.mengkePublicPath + '/custom/images/icon/logo.png');
    }
};
page.renderTotalData = function(){
    $('#totalPoint').html(this.totalData['totalPoints'] || 0);
    $('#maxDays').html(this.totalData['days'] || 0);
    $('#totalDays').html(this.totalData['totalDays'] || 0);
};
page.renderCalendar = function () {
    let thisPage = this;
    let monthDay = Dolphin.getCurMonthDay();
    let today = new Date();

    let dayArray = [], i, tr, td;
    let firstDay = monthDay.firstDay.getDay() || 7;
    for(i = 1; i < firstDay; i++){
        dayArray.push('');
    }
    for(i = 1; i <= monthDay.lastDay.getDate(); i++){
        dayArray.push(i);
    }
    let lastDay = monthDay.lastDay.getDay() || 7;
    for(i = lastDay + 1; i <= 7; i++){
        dayArray.push('');
    }

    let calendarArray = [];
    while(dayArray.length > 0){
        calendarArray.push(dayArray.splice(0, 7));
    }
    calendarArray.forEach(function(week){
        tr = $('<tr>').appendTo(thisPage.calendarDate);
        week.forEach(function(day){
            td = $('<td>').attr('day', day).html(day).appendTo(tr);
            if(day === today.getDate()){
                td.addClass('today');
            }
        });
    });

    $('#calendarTitle').html(today.getFullYear() + '年' + (today.getMonth() + 1) + '月');
};
page.alert = function(title, message){
    $('.signInfoTitle').html(title);
    $('.signInfoContent').html(message);
    $('.signInfo').show();
};

$(function () {
    page.init();
});




